package com.ellricky.tv.util;

import android.app.Activity;

import com.andr.common.http.callback.BaseCallback;
import com.andr.common.http.callback.GsonRespParser;
import com.andr.common.util.ToastUtil;
import com.google.gson.Gson;

import org.json.JSONObject;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

public abstract class TvEntityCallback<T> extends BaseCallback {
    private Class mClazz;

    public TvEntityCallback(Activity context) {
        this(context, true);
    }

    public TvEntityCallback(Activity context, boolean showLoading) {
        this(context, showLoading, "");
    }

    public TvEntityCallback(Activity context, boolean showLoading, String loadMsg) {
        super(context, showLoading, loadMsg);
        Type genType = this.getClass().getGenericSuperclass();
        if (genType != null) {
            Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
            this.mClazz = (Class) params[0];
        }
    }

    protected int dataFlag() {
        return 1;
    }

    protected void parseDataJO(String code, String msg, JSONObject dataJO) {
        super.parseDataJO(code, msg, dataJO);
        T entity = this.parseJsonObject(dataJO);
        if (entity != null) {
            if ("100".equals(code)) {
                this.onSuccess(entity, msg);
            } else {
                this.onErrorCode(entity, code, msg);
            }
        } else {
            this.onErrorCode(null, "-1001", "解析错误");
        }

    }

    public abstract void onSuccess(T var1, String var2);

    public void onErrorCode(T data, String code, String msg) {
        ToastUtil.show(this.mContext, msg);
    }

    private T parseJsonObject(JSONObject response) {
        T entity = null;
        if (this.mClazz != null) {
            Type gsonType = new GsonRespParser(this.mClazz, new Class[]{this.mClazz});
            entity = (new Gson()).fromJson(response.toString(), gsonType);
        }

        return entity;
    }
}
